<template>
	<el-dialog
		:title="title"
		:visible.sync="typeVisible"
		width="40%"
		:before-close="dialogBeforeClose"
		:close-on-click-modal="false"
		append-to-body
	>
		<el-form
			ref="form"
			:model="curTypes"
			:rules="rules"
			label-width="80px"
			:inline="false"
			size="normal"
		>
			<el-form-item label="类型名称" prop="name">
				<el-input v-model="curTypes.name"></el-input>
			</el-form-item>
			<el-form-item label="类型编码" prop="type">
				<el-input v-model="curTypes.type"></el-input>
			</el-form-item>
			<el-form-item label="备注">
				<el-input
					v-model="curTypes.remark"
					type="textarea"
					placeholder="请输入内容"
					:autosize="{ minRows: 2, maxRows: 4 }"
				></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="onSubmit">确定</el-button>
				<el-button @click="cancel">取消</el-button>
			</el-form-item>
		</el-form>
	</el-dialog>
</template>

<script>
import { getDictTypeModel } from '@/http/dict'
export default {
	props: {
		typeVisible: {
			type: Boolean,
			default: false,
		},
		title: {
			type: String,
			default: '',
		},
		type: {
			type: String,
			default: '',
		},
		curType: {
			type: Object,
			default: () => {
				return {}
			},
		},
	},
	data() {
		var typeValidator = this.typeFun
		return {
			rules: {
				name: [
					{ required: true, message: '请输入字典类型名称', trigger: 'blur' },
				],
				type: [
					{ required: true, message: '请输入字典类型编码', trigger: 'blur' },
					{ validator: typeValidator, trigger: 'blur' },
				],
				orgUuid: [{ required: true, message: '请选则机构', trigger: 'change' }],
			},
		}
	},
	computed: {
		curTypes() {
			return this.curType
		},
	},
	methods: {
		typeFun(rule, value, callback) {
			getDictTypeModel({ type: value }).then(({ data }) => {
				if (data?.head?.code == 200) {
					if (Object.keys(data?.data || {}).length > 0) {
						if (this.curTypes.id != data.data.id) {
							callback(new Error('该编码已经存在'))
						} else {
							callback()
						}
					} else {
						callback()
					}
				}
			})
		},
		dialogBeforeClose() {
			this.$emit('update:typeVisible', false)
			this.$emit('update:curType', {
				name: '',
				type: '',
				remark: '',
				orgUuid: '',
			})
			this.$nextTick(() => {
				this.$refs['form'].clearValidate()
			})
		},
		onSubmit() {
			this.$refs.form.validate(valid => {
				if (valid) {
					this.$emit('onSubmit', { ...this.curTypes }, this.type)
				} else {
					return false
				}
			})
		},
		cancel() {
			this.dialogBeforeClose()
		},
	},
}
</script>

<style lang="scss" scoped></style>
